package com.geekgo.ladder.core.util;

import com.geekgo.ladder.core.shiro.SysAuthorizingUser;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @author geekgo
 * @version 2016/12/22 14:21
 */
public final class WebUtil {
    private WebUtil(){

    }
    private final Logger LOG = LogManager.getLogger();


    /**
     * 获取当前登录用户
     * @return
     */
    public static final SysAuthorizingUser getCurrentUser(){
        try {
            Subject subject = SecurityUtils.getSubject();
            SysAuthorizingUser sysUser = (SysAuthorizingUser) subject.getPrincipal();
            if(null!=sysUser){
                return sysUser;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取当前登录用户ID
     * @return
     */
    public static final Long getCurrentUserId(){
        SysAuthorizingUser sysUser = getCurrentUser();
        return sysUser == null?null:sysUser.getId();
    }

    /**
     * 获取当前请求对象
     * @return
     */
    public static final HttpServletRequest getCurrentRequest(){
        try {
            return ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static final String getHost(){
        HttpServletRequest request = getCurrentRequest();
        String ip = request.getHeader("X-Forwarded-For");
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        if (ip.equals("127.0.0.1")|| ip.equals("0:0:0:0:0:0:0:1")) {
            // 根据网卡取本机配置的IP
            InetAddress inet = null;
            try {
                inet = InetAddress.getLocalHost();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            ip = inet.getHostAddress();
        }
        // 对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if (ip != null && ip.length() > 15) { // "***.***.***.***".length()
            // = 15
            if (ip.indexOf(",") > 0) {
                ip = ip.substring(0, ip.indexOf(","));
            }
        }
        return ip;
    }

    /**
     * 获取当前用户浏览器型号
     * @return
     */
    public static final String getUserBrowser(){
        UserAgent userAgent = UserAgent.parseUserAgentString(getCurrentRequest().getHeader("User-Agent"));
        Browser browser = userAgent.getBrowser();
        return browser.toString();
    }

    public static final String getUserOperatingSystem(){
        UserAgent userAgent = UserAgent.parseUserAgentString(getCurrentRequest().getHeader("User-Agent"));
        OperatingSystem operatingSystem = userAgent.getOperatingSystem();
        return operatingSystem.toString();
    }
}
